from app.utils import FakerUtil
from app.api.services.translators.abstract_translate import AbstractTranslator
from app.api.services.translators.edge.edge_lang import EdgeLang


class EdgeTranslator(AbstractTranslator):
    """
    Edge 翻译器
    """

    def __init__(self) -> None:
        super().__init__(
            "https://api-edge.cognitive.microsofttranslator.com/translate?from={from_lang}&to={to_lang}&api-version=3.0&includeSentenceLength=true",
            content_type="application/json",
        )
        self.orgin = "https://www.microsoft.com"
        self.referer = "https://www.microsoft.com/"
        self.auth_url = "https://edge.microsoft.com/translate/auth"

    def _get_request_url(self):
        vars = self._get_thread_local_vars()
        return self.url.format(
            from_lang=EdgeLang.from_lang(vars.src_lang).code,
            to_lang=EdgeLang.from_lang(vars.target_lang).code,
        )

    def _get_authorization(self):
        """
        _summary_: 获取授权信息
        Returns:
            _type_: 授权字符串，jwt格式,有效期10分钟
        """
        origin = FakerUtil().fake_origin()
        headers = {
            "Origin": origin,
            "Referer": origin + "/",
            "sec-mesh-client-arch": "x86_64",
            "sec-mesh-client-edge-channel": "stable",
            "sec-mesh-client-edge-version": "127.0.2651.98",
            "sec-mesh-client-os": "Windows",
            "sec-mesh-client-os-version": "10.0.22000",
            "sec-mesh-client-webview": "0",
        }
        response = self.http_client.get(
            url=self.auth_url,
            use_proxy=self._get_thread_local_vars().use_proxy,
            headers=headers,
        )
        if response.status_code != 200:
            # 增加其他补偿逻辑
            pass

        return response.text

    def _get_headers(self):
        headers = {
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "authorization": self._get_authorization(),
            "Cache-Control": "no-cache",
            "Content-Type": self.content_type,
            "Origin": self.orgin,
            "Pragma": "no-cache",
            "priority": "u=1, i",
            "Referer": self.referer,
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": FakerUtil().fake_user_agent(),
            "accept": "*/*",
        }
        return headers

    def _get_body(self):
        return [{"Text": self._get_thread_local_vars().content}]

    def _get_cookie(self):
        pass

    def _parse_repsonse(self, response):
        return response.json()[0]["translations"][0]["text"]
